package com.langfeiyes.pattern.proxy.dynamic.cglib;


import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 代理方法拦截器
 */
public class EmployeeMethodInterceptor implements MethodInterceptor {

    private Object target;
    public EmployeeMethodInterceptor(Object target){
        this.target = target;
    }
    /**
     * 拦截方法实现代理
     * 参数1：真实对象
     * 参数2：代理方法
     * 参数3：代理方法参数
     * 参数4：代理对象
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        String name = method.getName();
        if("save".equals(name) && !"admin".equals(SessionHolder.getCurrentUser())){
            throw new RuntimeException("当前非admin用户，不能执行save操作");
        }
        return methodProxy.invokeSuper(o, objects);
    }

    public Object getProxy(){
        Enhancer enhancer =new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }
}
